/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JoUpPanel.java
 *
 * Created on 01/12/2011, 14:47:15
 */
package proj5labbd.graphics.jornal;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class JoUpPanel extends OperationPanel {

    /** Creates new form JoUpPanel */
    public JoUpPanel(JornalFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtUpdate.addActionListener(new JornalAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbTitulo = new javax.swing.JLabel();
        jtxtTitulo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jlbDescricao = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtxaDesc = new javax.swing.JTextArea();
        jlbAbr = new javax.swing.JLabel();
        jcmbAbr = new javax.swing.JComboBox();
        jtxtDur = new javax.swing.JTextField();
        jbtUpdate = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbTitulo.setText("Título");

        jLabel1.setText("Duração");

        jlbDescricao.setText("Descrição");

        jtxaDesc.setColumns(20);
        jtxaDesc.setRows(5);
        jScrollPane2.setViewportView(jtxaDesc);

        jlbAbr.setText("Abrangência");

        jcmbAbr.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "REGIONAL", "ESTADUAL", "NACIONAL", "INTERNACIONAL" }));

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jpnInsertLayout.createSequentialGroup()
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE)
                            .addContainerGap())
                        .addGroup(jpnInsertLayout.createSequentialGroup()
                            .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jlbDescricao, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpnInsertLayout.createSequentialGroup()
                                    .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jlbTitulo))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(jpnInsertLayout.createSequentialGroup()
                                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGap(165, 165, 165))
                                        .addComponent(jtxtDur))))
                            .addGap(12, 12, 12)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnInsertLayout.createSequentialGroup()
                        .addComponent(jlbAbr)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcmbAbr, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbTitulo)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtDur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbDescricao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcmbAbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbAbr))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtUpdate.setText("Atualizar");

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbUpdate);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jpnInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jbtUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     Método para resgatar as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtUpdate;
    private javax.swing.JComboBox jcmbAbr;
    private javax.swing.JLabel jlbAbr;
    private javax.swing.JLabel jlbDescricao;
    private javax.swing.JLabel jlbTitulo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbUpdate;
    private javax.swing.JTextArea jtxaDesc;
    private javax.swing.JTextField jtxtDur;
    private javax.swing.JTextField jtxtTitulo;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata a tabela jornal
     */
    private void setupTable() throws SQLException {
        
        String [] fieldsCo = {"jornal.idPr","jornal.tituloPr","jornal.descricaoPr",
            "jornal.idDe","departamento.nomeDe" };
        String [] titlesCo = {"ID Jornal","Titulo","Descrição","ID Departamento","Nome do departamento"};
        String [] paramsCo = {"jornal.idDe=departamento.idDe"};
        String [][] resultCo = dbInterface.view(fieldsCo,paramsCo,new String[]{"jornal","departamento"});

        DefaultTableModel model = new DefaultTableModel(resultCo,titlesCo);
        jtbUpdate.setModel(model);
        
    }
    
    class JornalAction implements ActionListener {
        
        /*
         * Controla os eventos de atualização
         */
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtxtTitulo.getText().trim().compareTo("") != 0) {
                fields.add("jornal.tituloPr='"+jtxtTitulo.getText()+"'");
            }
            
            if (jtxaDesc.getText().trim().compareTo("") != 0) {
                fields.add("jornal.descricaoPr='"+jtxaDesc.getText()+"'");
            }
            
            if (jtxtDur.getText().trim().compareTo("") != 0) {
                fields.add("jornal.duracaoJo='"+jtxtDur.getText()+"'");
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String s;
                String [] params = new String[1];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        params[0] = "jornal.idPr="+jtbUpdate.getValueAt(rows[i],0).toString();
                        dbInterface.update(fieldsArray, params,
                                new String[]{"jornal"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }

}
